//
//  GoodListViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/12.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "GoodListViewController.h"
#import "GoodListLeftTableViewCell.h"
#import "GoodListRightTableViewCell.h"
#import "ShopInfoViewController.h"
#import "GoodInfoViewController.h"
#import "MethodOfPaymentView.h"
#import "TheMembershipCardToPayView.h"
#import "LackOfBalanceView.h"
#import "MemberPrepaidPhoneViewController.h"
#import "MakeSureTheOrderViewController.h"
#define groupBuyingBtnX (SCREEN_WIDTH/2 - btnW)/2
@interface GoodListViewController ()<UITableViewDelegate , UITableViewDataSource>
{
    NSString *chooseLeftIndex;
    int money; //总金钱数
}
Strong UIView * typeBGView;//团购、外卖背景
Strong UIButton * groupBuyingBtn;//团购按钮
Strong UIButton * takeOutBtn;//外卖按钮
Strong UIView * slideView;//按钮下蓝色线
Assign BOOL isGroupClick;//判断是否为团购

Strong UITableView *leftTableView;
Strong UITableView *rightTableView;
Strong NSMutableArray *leftDataArray; /**<*/
Strong NSMutableArray *rightDataArray; /**<*/
Strong UIView *footView;
Strong UILabel *moneyLabel;
Strong SDCycleScrollView *sdcView;
- (void)rightBarButtonItemClick;
Strong NSMutableArray *numberArray; /**<*/
Strong NSMutableArray *cIdArray; /**<商品ID（字符串，以“，”拼接） */
Strong NSMutableArray *numberArr; /**<购买数量（字符串，以“，”拼接）-必须与商品ID一一对应 */

@end

//网络
@implementation GoodListViewController (NetWorking)

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_id":self.s_id};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity/displayAllItemsInTheStore.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSString *str = [[NSURL URLOffsetIPWithString:responseObject[@"obj"][@"picture"]]absoluteString];
            self.sdcView.imageURLStringsGroup = @[str];
            self.leftDataArray = responseObject[@"obj1"];
            self.rightDataArray = responseObject[@"obj2"];
            for (int i = 0 ; i < self.rightDataArray.count; i ++) {
                NSMutableArray *addArray = @[].mutableCopy;
                NSArray *array = self.rightDataArray[i];
                for (int y = 0 ; y < array.count; y ++) {
                    [addArray addObject:@"0"];
                }
                [self.numberArray addObject:addArray];
            }
//            [self.view sd_addSubviews:@[self.leftTableView, self.rightTableView, self.sdcView, self.footView]];
            [self.view sd_addSubviews:@[self.sdcView ,self.typeBGView, self.leftTableView , self.rightTableView ,  self.footView]];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


/**
 商城直接购买商品生成的订单信息
 */
- (void)newOrderInformation{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"sId":self.s_id,
                                 @"total":[NSString stringWithFormat:@"%d",money],
                                 @"cId":[self.cIdArray componentsJoinedByString:@","],@"number":[self.numberArr componentsJoinedByString:@","]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Order/newOrderInformation.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
                MakeSureTheOrderViewController *vc = [MakeSureTheOrderViewController new];
                vc.so_id = responseObject[@"obj"][@"so_id"];
                [self.navigationController pushViewController:vc animated:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation GoodListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"店铺首页";
    chooseLeftIndex = @"0";
    UIButton * rightButton = [[UIButton alloc]init];
    rightButton.size = CGSizeMake(50, 20);
    [rightButton setTitle:@"店铺详情" forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:DEF_FontSize_11];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 3;
    rightButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    rightButton.layer.borderWidth = 1;
    [rightButton addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置barbutton
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - click
- (void)rightBarButtonItemClick{
    if (!self.s_id) {
        return;
    }
    ShopInfoViewController *vc = [ShopInfoViewController new];
    vc.sId = self.s_id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)typeButtonClick{
    NSLog(@"结算");
    if (self.cIdArray.count == 0) {
        ShowMessage(@"未选择商品");
        return;
    }
    [self newOrderInformation];
    
}

- (void)typeBtnClick:(UIButton *)sender{
    
    if (sender.frame.origin.x + 1 > SCREEN_WIDTH/2 ) {
        self.isGroupClick = NO;
        self.groupBuyingBtn.selected = NO;
        self.takeOutBtn.selected = YES;
    }else{
        self.isGroupClick = YES;
        self.groupBuyingBtn.selected = YES;
        self.takeOutBtn.selected = NO;
    }
    __weak typeof (self)weak = self;
    [UIView animateWithDuration:0.3 animations:^{
        weak.slideView.x = sender.x;
    }];
}

#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.leftTableView) {
        return self.leftDataArray.count;
    }
    NSArray *array = self.rightDataArray[[chooseLeftIndex intValue]];
    return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.leftTableView) {
        GoodListLeftTableViewCell *cell = [GoodListLeftTableViewCell cellForTableView:tableView];
        cell.indexPath = indexPath;
        cell.chooseIndex = chooseLeftIndex;
        cell.model = self.leftDataArray[indexPath.row];
        //cell.accessoryType = indexPath.row == 3 ?  UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
        return cell;
    }
    GoodListRightTableViewCell *cell = [GoodListRightTableViewCell cellForTableView:tableView];
    cell.number = self.numberArray[indexPath.section][indexPath.row];
    cell.model = self.rightDataArray[indexPath.section][indexPath.row];
    cell.getAddNumberClick = ^{
        [self.cIdArray removeAllObjects];
        [self.numberArr removeAllObjects];
        int a = [self.numberArray[indexPath.section][indexPath.row] intValue];
        a ++;
        self.numberArray[indexPath.section][indexPath.row] = [NSString stringWithFormat:@"%d",a];
        [self.rightTableView reloadData];
        int number = 0;
         money = 0;
        for (int i = 0 ; i < self.numberArray.count; i ++) {
            NSArray *array = self.numberArray[i];
            for (int y = 0; y <  array.count; y ++) {
                if (![self.numberArray[i][y] isEqualToString:@"0"]) {
                    number += [self.numberArray[i][y] intValue];
                    money += [self.rightDataArray[i][y][@"unit_price"] intValue] * [self.numberArray[i][y] intValue];
                    [self.numberArr addObject:[NSString stringWithFormat:@"%d",[self.numberArray[i][y] intValue]]];
                    [self.cIdArray addObject:self.rightDataArray[i][y][@"c_id"] ];
                }
            }
        }
        self.moneyLabel.attributedText = [self getAttributeName:[NSString stringWithFormat:@"%.2f",(float)money] info:[NSString stringWithFormat:@"%d",number]];
    };
    cell.getDeleteNumberClick = ^{
        [self.cIdArray removeAllObjects];
        [self.numberArr removeAllObjects];
        int a = [self.numberArray[indexPath.section][indexPath.row] intValue];
        a --;
        self.numberArray[indexPath.section][indexPath.row] = [NSString stringWithFormat:@"%d",a];
        [self.rightTableView reloadData];
        int number = 0;
         money = 0;
        for (int i = 0 ; i < self.numberArray.count; i ++) {
            NSArray *array = self.numberArray[i];
            for (int y = 0; y <  array.count; y ++) {
                if (![self.numberArray[i][y] isEqualToString:@"0"]) {
                    number += [self.numberArray[i][y] intValue];
                    money += [self.rightDataArray[i][y][@"unit_price"] intValue] * [self.numberArray[i][y] intValue];
                    [self.numberArr addObject:[NSString stringWithFormat:@"%d",[self.numberArray[i][y] intValue]]];
                    [self.cIdArray addObject:self.rightDataArray[i][y][@"c_id"] ];
                }
            }
        }
        self.moneyLabel.attributedText = [self getAttributeName:[NSString stringWithFormat:@"%.2f",(float)money] info:[NSString stringWithFormat:@"%d",number]];
    };
    //cell.accessoryType = indexPath.row == 3 ?  UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.leftTableView) {
        chooseLeftIndex = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        [self.leftTableView reloadData];
        [self.rightTableView reloadData];
    }else{
        GoodInfoViewController *vc = [GoodInfoViewController new];
        vc.s_id = self.s_id;
        vc.gId = self.rightDataArray[indexPath.section][indexPath.row][@"c_id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58 / WIDTH_5S_SCALE;
}

#pragma mark - init

- (SDCycleScrollView *)sdcView{
    if (!_sdcView) {
        _sdcView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150/WIDTH_5S_SCALE)];
        _sdcView.backgroundColor = getColor(mainColor);
        _sdcView.autoScrollTimeInterval = 3.0;
        _sdcView.backgroundColor = getColor(@"bfbfbf");
        _sdcView.pageControlDotSize = CGSizeMake(11, 11);
        _sdcView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _sdcView.currentPageDotImage = [UIImage imageNamed:@"homepage_banner_point"];
        _sdcView.pageDotImage = [UIImage imageNamed:@"homepage_banner_circle"];
        __block typeof(self) bSelf = self;
        _sdcView.clickItemOperationBlock = ^(NSInteger currentIndex) {
            
        };
        
    }
    return _sdcView;
}

- (UILabel *)moneyLabel{
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH - 86 / WIDTH_5S_SCALE, 50 / WIDTH_5S_SCALE - 1)];
        _moneyLabel.backgroundColor = getColor(@"ffffff");
        _moneyLabel.textColor = getColor(mainColor);
        _moneyLabel.textAlignment = NSTextAlignmentCenter;
        _moneyLabel.attributedText = [self getAttributeName:@"0.00" info:@"0"];
    }
    return _moneyLabel;
}

- (NSAttributedString *)getAttributeName:(NSString *)name info:(NSString *)info{
    NSMutableAttributedString *attStr = [NSMutableAttributedString new];
    NSAttributedString *nameAtt = [[NSAttributedString alloc]initWithString:@"总计:" attributes:@{NSFontAttributeName:DEF_FontSize_17}];
    NSAttributedString *infoAtt = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"(数量:%@)",info] attributes:@{NSFontAttributeName:DEF_FontSize_12}];
    [attStr appendAttributedString:nameAtt];
    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:name]];
    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"元"]];
    [attStr appendAttributedString:infoAtt];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setParagraphSpacing:16];//调整行间距
    [paragraphStyle setAlignment:NSTextAlignmentCenter];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attStr.mutableString length])];
    
    return attStr;
}

- (UIView *)footView{
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50 / WIDTH_5S_SCALE - 64, SCREEN_WIDTH, 50 / WIDTH_5S_SCALE)];
        _footView.backgroundColor = getColor(mainColor);
        UIButton *typeButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 86 / WIDTH_5S_SCALE, 0, 86 / WIDTH_5S_SCALE, 50 / WIDTH_5S_SCALE)];
        typeButton.backgroundColor = getColor(mainColor);
        typeButton.titleLabel.font = DEF_FontSize_14;
        [typeButton setTitle:@"结算" forState:UIControlStateNormal];
        [typeButton setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
        [typeButton addTarget:self action:@selector(typeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_footView sd_addSubviews:@[typeButton , self.moneyLabel]];
    }
    return _footView;
}

- (UITableView *)leftTableView{
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.typeBGView.bottom, 94 / WIDTH_5S_SCALE, SCREEN_HEIGHT - 64 - 150 / WIDTH_5S_SCALE - 50 / WIDTH_5S_SCALE) style:UITableViewStyleGrouped];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableView.sectionFooterHeight = .01;
        _leftTableView.sectionHeaderHeight = .01;
        _leftTableView.tableFooterView = [UIView new];
        _leftTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.showsHorizontalScrollIndicator = NO;
        _leftTableView.backgroundColor = getColor(@"ffffff");
    }
    return _leftTableView;
}

- (UITableView *)rightTableView{
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(94 / WIDTH_5S_SCALE, self.leftTableView.top, SCREEN_WIDTH - 94 / WIDTH_5S_SCALE, SCREEN_HEIGHT - 64 - 150 / WIDTH_5S_SCALE - 50 / WIDTH_5S_SCALE) style:UITableViewStyleGrouped];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _rightTableView.sectionFooterHeight = .01;
        _rightTableView.sectionHeaderHeight = .01;
        _rightTableView.tableFooterView = [UIView new];
        _rightTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.showsHorizontalScrollIndicator = NO;
        _rightTableView.backgroundColor = getColor(@"ffffff");
    }
    return _rightTableView;
}



#pragma mark - data

- (NSMutableArray *)leftDataArray{
    if (!_leftDataArray) {
        _leftDataArray  = @[
                            ].mutableCopy;
    }
    return _leftDataArray;
}

- (NSMutableArray *)rightDataArray{
    if (!_rightDataArray) {
        _rightDataArray  = @[].mutableCopy;
    }
    return _rightDataArray;
}

- (void)setS_id:(NSString *)s_id{
    _s_id = s_id;
    [self getData];
}

- (NSMutableArray *)numberArray{
    if (!_numberArray) {
        _numberArray = @[].mutableCopy;
    }
    return _numberArray;
}

- (NSMutableArray *)numberArr{
    if (!_numberArr) {
        _numberArr = @[].mutableCopy;
    }
    return _numberArr;
}

- (NSMutableArray *)cIdArray{
    if (!_cIdArray) {
        _cIdArray = @[].mutableCopy;
    }
    return _cIdArray;
}
//150/WIDTH_5S_SCALE
- (UIView *)typeBGView{
    if (!_typeBGView) {
        _typeBGView = [[UIView alloc] initWithFrame:CGRectMake(0, self.sdcView.bottom, SCREEN_WIDTH, 83/WIDTH_5S_SCALE)];
        _typeBGView.backgroundColor = [UIColor whiteColor];
        
        int btnW = 50/WIDTH_5S_SCALE;
//        int groupBuyingBtnX = (SCREEN_WIDTH/2 - btnW)/2;
        //团购
        UIButton * groupBuyingBtn = [[UIButton alloc] initWithFrame:CGRectMake(groupBuyingBtnX, 0, btnW, 36/WIDTH_5S_SCALE)];
        [groupBuyingBtn setTitle:@"团购" forState:UIControlStateNormal];
        [groupBuyingBtn setTitleColor:getColor(mainColor) forState:UIControlStateSelected];
        [groupBuyingBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [groupBuyingBtn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_typeBGView addSubview:groupBuyingBtn];
        groupBuyingBtn.selected = YES;
        self.groupBuyingBtn = groupBuyingBtn;
        //外卖
        UIButton * takeOutBtn = [[UIButton alloc] initWithFrame:CGRectMake(groupBuyingBtnX + SCREEN_WIDTH/2, 0, btnW, 36/WIDTH_5S_SCALE)];
        [takeOutBtn setTitle:@"外卖" forState:UIControlStateNormal];
        [takeOutBtn setTitleColor:getColor(mainColor) forState:UIControlStateSelected];
        [takeOutBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [takeOutBtn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_typeBGView addSubview:takeOutBtn];
        self.takeOutBtn = takeOutBtn;
        //线
        UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, groupBuyingBtn.bottom, SCREEN_WIDTH, 1)];
        lineView.backgroundColor = getColor(@"eeeeee");
        [_typeBGView addSubview:lineView];
        self.slideView = [[UIView alloc] initWithFrame:CGRectMake(groupBuyingBtn.left, lineView.top - 1, 50/WIDTH_5S_SCALE, 2)];
        self.slideView.backgroundColor = getColor(mainColor);
        [_typeBGView addSubview:self.slideView];
        //代金券
        int couponBGViewH = 19/WIDTH_5S_SCALE;
        int couponBGViewCenterY = (_typeBGView.height - lineView.bottom - couponBGViewH)/2 + couponBGViewH/2 + lineView.bottom;
        
        UIView * couponBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 86/WIDTH_5S_SCALE, 19/WIDTH_5S_SCALE)];
        couponBGView.center = CGPointMake(SCREEN_WIDTH/2, couponBGViewCenterY);
        couponBGView.backgroundColor = getColor(@"fdf9c9");
        [_typeBGView addSubview:couponBGView];
    }return _typeBGView;
}

@end
